import 'dart:async';
import 'dart:convert';
import 'package:drm/http/dioUtil.dart';
import 'package:drm/http/http_url.dart';

import 'package:drm/http/date_result.dart';
import 'package:drm/entity_factory.dart';

class ActionDo {
  static Future<DateResult<List<T>>> getDate<T>(Map<String, String> data,
      {String postUrl = ''}) async {
    List<T> datas;
    DateResult<List<T>> dateResult;
    try {
      if (postUrl.isEmpty) {
        postUrl = AppUrl.getTjDateUrl();
      }
      Result result = await DioUtil.post(postUrl, data: data);
      List dateList = jsonDecode(result.data);
      datas =
          dateList.map((item) => EntityFactory.generateOBJ<T>(item)).toList();
      dateResult = DateResult(
          isSuccess: result.isSuccess,
          code: result.code,
          message: result.message,
          data: datas);
    } catch (e) {
      dateResult = DateResult(isSuccess: false, message: '请求错误');
    }
    return dateResult;
  }


  static Future<DateResult<T>> getInfoDate<T>(Map<String, String> data,
      {String postUrl = ''}) async {
    DateResult<T> dateResult;
    try {
      if (postUrl.isEmpty) {
        postUrl = AppUrl.getTjDateUrl();
      }
      Result result = await DioUtil.post(postUrl, data: data);

      print('ActionDo  :  ${result.toString()}');

      T resultData = EntityFactory.generateOBJ<T>(jsonDecode(result.data));
      dateResult = DateResult(
          isSuccess: result.isSuccess,
          code: result.code,
          message: result.message,
          data: resultData);
    } catch (e) {
      dateResult = DateResult(isSuccess: false, message: '请求错误');
    }
    return dateResult;
  }


  static Future<DateResult<Map>> getListDateHandTotal<T>(Map<String, String> params,
      {String postUrl = ''}) async {
    List<T> datas;
    int total = 0 ;

    DateResult<Map> dateResult;
    Result result;
    try {
      if (postUrl.isEmpty) {
        postUrl = AppUrl.getTjDateUrl();
      }
       result = await DioUtil.post(postUrl, data: params);

      Map<String,dynamic > dateList = jsonDecode(result.data);
      if (dateList.containsKey('total')) {
        total = dateList['total'];
      }
      if (dateList.containsKey('rows')) {
        List rows = dateList['rows'];
        datas = rows.map((item) => EntityFactory.generateOBJ<T>(item)).toList();
      }

      Map data = {'total':total,'rows':datas} ;
      dateResult = DateResult(
          isSuccess: result.code != 200 ? false:  result.isSuccess,
          code: result.code,
          message: result.message,
          data: data);
    } catch (e) {
      print(e.toString());
      dateResult = DateResult(isSuccess: false, message: result.message);
    }
    return dateResult;
  }

}
